package project.taobao.commons.activemq.consumer.imple;

import org.apache.activemq.ActiveMQConnectionFactory;
import project.taobao.commons.activemq.utils.ActiveMqUtils;

import javax.jms.*;

public class JMSConsumer {
    private Object data;

    // methods
    public Object consumerMessage(String queueName){
        ActiveMQConnectionFactory connectionFactory = ActiveMqUtils.getAcMQConnectionFactory();
        Connection connection = null;
        Session session = null;
        try{
            // 我总感觉这里有点问题， 要是访问多起，会不会炸？  不弄连接池的话
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Queue destination = session.createQueue(queueName);
            MessageConsumer messageConsumer = session.createConsumer(destination);
            messageConsumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    try{
                        data = ((MapMessage) message).getObject("data");
                    } catch (Exception e){

                    }
                }
            });
            session.commit();
        } catch (Exception e){

        } finally {
            try{
                if(connection != null){
                    connection.close();
                    return data;
                }
            } catch (Exception e){

            }
        }
        return null;
    }

    /**
     * 获得回返的信息
     * @return
     */
    public Object getInfomation(){
        Object dataG = null;
        try{
            while(getData() == null){
                Thread.currentThread().sleep(10);
            }
            dataG = getData();
            setData(null);
            return dataG;
        } catch (Exception e){

        }
        return null;
    }

    // getters, setters
    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }


    // constructors
}
